<!DOCTYPE html>
<html>
  <head>
    <title>Redux basic</title>
    <script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
  </head>
  <body>
    <style>
      .sample {
        position: absolute;
        left: 0px;
        width: 100px;
        height: 20px;
        transition-property: left;
        transition-duration: 2s;
        /* transition-timing-function: ease; */
      }
      .sample:hover {
        left: 420px;
      }
    </style>
    <div style="position: relative;height: 100px;"><div class="sample">123</div></div>

    <div>
      <p><span id="colorEl">Watch my color.</span> <button id="red">RED</button> <button id="green">GREEN</button> <button id="toggle">TOGGLE</button></p>
    </div>

    <script type="text/javascript">
      var initialState = {
        color: 'red'
      };

      function color(state, action) {
        if (typeof state === 'undefined') {
          return initialState;
        }

        switch (action.type) {
          case 'RED':
            // return { color: 'red' };
            state.color = 'red';
            return state;
          case 'GREEN':
            // return { color: 'green' };
            state.color = 'green';
            return state;
          case 'TOGGLE':
            return state.color === 'red' ? { color: 'green' } : { color: 'red' };
          default:
            return state;
        }
      }

      var store = Redux.createStore(color);
      var colorEl = document.getElementById('colorEl');

      function renderValue() {
        colorEl.style.color = store.getState().color;
      }

      // renderValue()
      //注册监听器
      store.subscribe(renderValue);

      document.getElementById('red').addEventListener('click', function() {
        store.dispatch({
          type: 'RED'
        });
      });

      document.getElementById('green').addEventListener('click', function() {
        store.dispatch({
          type: 'GREEN'
        });
      });

      document.getElementById('toggle').addEventListener('click', function() {
        store.dispatch({
          type: 'TOGGLE'
        });
      });

      // array的reduce方法
      // array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
      // total   必需。初始值, 或者计算结束后的返回值。
      // currentValue    必需。当前元素
      // currentIndex    可选。当前元素的索引
      // arr 可选。当前元素所属的数组对象。
      // initialValue  可选   代表total的初始类型和初始值

      var arr = [1, 2, 3, 4, 5, 6];
      var result = arr.reduce((sum, val) => {
        return sum + val;
      });

      console.log(result);
    </script>
  </body>
</html>
